import { MessageType, request, useApp, postMessage } from '@inbiz/utils';
import { useSelectPage } from '@editor';
import { useRef, useState } from 'react';
import { getMessage } from '@inbiz/react';

export const random = (): string => {
  const s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
  let l = s.length;
  let n = '';
  for (let i = 1; i < 30; i++) {
    if (i % 6 || !i) {
      n += s.charAt(Math.floor(Math.random() * l));
    } else {
      n += '-';
    }
  }
  return n;
};

export const realtionDataSet = (origin, current, list, select) => {
  const optionList = origin?.allInfo?.Children || [];
  const newOption = current.filter((ele) =>
    optionList.every((child) => child.ObjectValue !== ele.value),
  );

  const childOption = newOption.filter((ele) => ele.value && ele.value.length > 0);

  const target =
    Object.keys(origin?.allInfo || {}).length === 0
      ? []
      : [
        {
          outId: origin?.allInfo?.OutId,
          objectName: origin?.allInfo?.ObjectName,
          objectValue: origin?.allInfo?.ObjectValue,
          type: 200,
          parentOutId: select.OutId,
          isCreate: origin?.allInfo?.isCreate,
          pageOutId: select.OutId,
        },
      ];
  if (childOption.length !== 0) {
    target.push(
      ...childOption.map((ele) => ({
        outId: random(),
        objectName: ele.label,
        objectValue: ele.value,
        type: 201,
        parentOutId: origin?.allInfo?.OutId,
        pageOutId: select.OutId,
      })),
    );
  }
  const leftList = (list || []).filter((ele) => ele.value !== origin.value);
  target.push(
    ...leftList.map((ele) => ({
      outId: ele?.allInfo?.OutId,
      objectName: ele?.allInfo?.ObjectName,
      objectValue: ele?.allInfo?.ObjectValue,
      type: 200,
      parentOutId: select.OutId,
      isCreate: true,
      pageOutId: select.OutId,
    })),
  );
  return target;
};

export const hasAuth = (data, type, authList, authType?: string) => {
  const row = (data.table || []).filter((t) => t[authType || 'operationType'] === type)[0];
  const len = (authList || []).length;
  const groupId = data.auth;
  const hasFlag = (authList || []).filter(
    (ele) => ele.GroupOutId === groupId && ele.Button === row?.operationflag,
  );

  return {
    operationflag: row?.operationflag,
    auth: len === 0 || hasFlag.length === 0 ? true : hasFlag[0]?.IsHavePerm,
  };
};

export const useAuth = () => {
  const [choosedAuth, setChoosedAuth] = useState<{
    allInfo?: {
      Children?: {
        ObjectValue: string;
        ObjectName: string;
      }[];
    };
  }>({});
  const [select] = useSelectPage();
  const appInfo = useApp();
  const newAuthList = useRef([]);

  const changeHandle = (data, addList) => {
    newAuthList.current = addList ?? [];
    setChoosedAuth(data || {});
  };

  const generateFlag = async (flagList: { value: string; label: string }[]) => {
    // 将多语言部分转换为对应的语言模式
    flagList = flagList?.map((item: any) => {
      return {
        ...item,
        label: getMessage(item.label),
      };
    });
    // 如果未选中选中权限，则不调用接口保存
    if (!Object.keys(choosedAuth)?.length) {
      return;
    }
    const relationData = realtionDataSet(choosedAuth, flagList, newAuthList.current, select);
    if (relationData.length === 0 || (!relationData[0].isCreate && relationData.length === 1)) {
      return Promise.resolve();
    }
    const version = InbizConfig.API_VERSION;
    await request(`/inbiz/api/services/engines/v${version}/menuRelation/orUpdateButtonGroup`, {
      method: 'POST',
      data: {
        pageOutId: select.OutId,
        relationData: [
          {
            objectName: select.DisplayName,
            objectValue: select.Route,
            outId: select.OutId,
            parentOutId: null,
            type: 100,
            pageOutId: select.OutId,
          },
          ...relationData,
        ],
        siteOutId: appInfo?.SiteInfo?.OutId,
        dataVersionId: appInfo?.DataVersionId
      },
    });
    // message通讯
    let messageData: MessageType = {
      module: 'menuRelation',
      event: 'save',
      data: {
        pageOutId: select.OutId,
        siteOutId: appInfo?.SiteInfo?.OutId,
        dataVersionId: appInfo?.DataVersionId
      },
    };
    postMessage(messageData);
  };

  return [choosedAuth, changeHandle, generateFlag] as const;
};
